//
//  AppleIDLoginUtils.m
//  GC_OC
//
//  Created by Tianbao Wang on 2022/5/26.
//

#import "AppleIDLoginUtils.h"

API_AVAILABLE(ios(13.0))
@interface AppleIDLoginUtils ()
@property(nonatomic, strong) void (^ complete)(ASAuthorizationAppleIDCredential*, NSError*);

@end

@implementation AppleIDLoginUtils

+ (instancetype)shared {
    static AppleIDLoginUtils *sharedAccountManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedAccountManagerInstance = [[self alloc] init];
    });
    return sharedAccountManagerInstance;
}

- (void)authrization: (void (^)(ASAuthorizationAppleIDCredential*, NSError*))block  API_AVAILABLE(ios(13.0)){
    self.complete = block;
    // 基于用户的Apple ID授权用户，生成用户授权请求的一种机制
    ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
    // 创建新的AppleID 授权请求
    ASAuthorizationAppleIDRequest *appleIDRequest = [appleIDProvider createRequest];
    // 在用户授权期间请求的联系信息
    appleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
    // 由ASAuthorizationAppleIDProvider创建的授权请求 管理授权请求的控制器
    ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[appleIDRequest]];
    // 设置授权控制器通知授权请求的成功与失败的代理
    authorizationController.delegate = self;
    // 设置提供 展示上下文的代理，在这个上下文中 系统可以展示授权界面给用户
    authorizationController.presentationContextProvider = self;
    // 在控制器初始化期间启动授权流
    [authorizationController performRequests];
}

- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){
    return [UIApplication sharedApplication].delegate.window;
}

- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)){
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        //用于后台像苹果服务器验证身份信息
        if (self.complete) {
            self.complete((ASAuthorizationAppleIDCredential *)authorization.credential, nil);
        }
    }
}
    
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
    if (self.complete) {
        self.complete(nil, error);
    }
}

@end
